package com.ninetaildemonfox.zdl.socialproject.mvp.presenter;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.JsonObject;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.Preferences;
import com.hyphenate.easeui.utils.map.JSONUtils;
import com.kongzue.dialog.interfaces.OnDismissListener;
import com.kongzue.dialog.v3.TipDialog;
import com.kongzue.dialog.v3.WaitDialog;
import com.ninetaildemonfox.zdl.ninetaildemonfox.utils.AppManager;
import com.ninetaildemonfox.zdl.socialproject.config.Constants;
import com.ninetaildemonfox.zdl.socialproject.http.https.Model;
import com.ninetaildemonfox.zdl.socialproject.mvp.contract.LoginContract;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.AuthenticateLoginActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.EditorialMaterialsActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.MainActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.SelectiveSexActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.WelcomeActivity;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;
import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 创建人： Nine tails fox
 * 创建时间： 2019/7/29
 * 功能描述：登录界面的P 层
 * 联系方式：1037438704@qq.com
 *
 * @author NineTailDemonFox
 */

public class LoginPresenter {


    private AppCompatActivity me;

    public void setContext(AppCompatActivity context) {
        me = context;
    }

    private LoginContract loginContract;

    public LoginPresenter(LoginContract loginContract) {
        this.loginContract = loginContract;
    }

    /**
     * 登录接口
     */
    public void getLogin(String userName, String psd) {
        if (TextUtils.isEmpty(userName)) {
            ToastUtil.show("请填写用户名");
            return;
        }
        if (TextUtils.isEmpty(psd)) {
            ToastUtil.show("请填写密码");
            return;
        }
        loginContract.showLoading();
        Model.getInstance().getUserApi().getLogin("Member/login", userName, psd).enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                String s = String.valueOf(response.body());
                Logger.json(s);
                if (s == null) {
                    return;
                }
                Map<String, String> map = JSONUtils.parseKeyAndValueToMap(s);
                if (map.get("code").equals("1")) {
                    Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                    loginContract.loginSuccess(data);
                } else {
                    loginContract.loginFailed(map.get("message"));
                    WaitDialog.dismiss();
                }

            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                loginContract.loginFailed(t.getMessage());
                WaitDialog.dismiss();
            }
        });
    }

    /**
     * 三方登录
     */
    public void getThreeLogin(final String count) {
        Platform plat = null;
        if (count.equals("1")) {
            plat = ShareSDK.getPlatform(QQ.NAME);
        } else {
            plat = ShareSDK.getPlatform(Wechat.NAME);
        }
        plat.removeAccount(true); //移除授权状态和本地缓存，下次授权会重新授权
        plat.SSOSetting(false); //SSO授权，传false默认是客户端授权，没有客户端授权或者不支持客户端授权会跳web授权
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                platform.getName();
                platform.getId();
                PlatformDb db = platform.getDb();
                db.getToken();
                db.getUserId();
                db.getUserIcon();
                Log.d("PlatformDb", "=========== platform.getId()============" + platform.getId());
                Log.d("PlatformDb", "=========== platform.getName()============" + platform.getName());
                Log.d("PlatformDb", "=========== db.getToken()============" + db.getToken());
                Log.d("PlatformDb", "=========== db.getUserId()============" + db.getUserId());
                Log.d("PlatformDb", "=========== db.getUserIcon()============" + db.getUserIcon());
                Model
                        .getInstance()
                        .getUserApi()
                        .getThreeLogin(db.getUserId() + "", platform.getName(), count + "","2").enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Map<String, String> map = Constants.codeGet(me, response);
                        if (map == null) {
                            return;
                        }
                        final Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                        if (data == null) {
                            return;
                        }
                        if (TextUtils.isEmpty(data.get("account"))) {
                            String token = data.get("token");
                            AuthenticateLoginActivity.start(me,token ,3,data.get("bind_id"));
                        } else {
                            Preferences.getInstance().commit(me, "name", "phone", data.get("account"));
                            Preferences.getInstance().commit(me, "user", "token", data.get("token"));
                            Preferences.getInstance().commit(me, "user", "sex", data.get("sex"));
                            Preferences.getInstance().commit(me, "user", "vip", data.get("vip"));
                            //判断是否已经填写
                            Preferences.getInstance().commit(me, "user", "nickname", data.get("nickname"));
                            //判断是否已经填写
                            Preferences.getInstance().commit(me, "user", "invite_code", data.get("invite_code"));
                            //环信登录
                            huanxin(data);

                            TipDialog.show(me, "登录成功", TipDialog.TYPE.SUCCESS).setOnDismissListener(new OnDismissListener() {
                                @Override
                                public void onDismiss() {
                                    // 性别 1男 2 女
                                    String string = Preferences.getInstance().getString(me, "user", "sex");
                                    Logger.d("=========登录界面获取的性别==========" + string);
                                    if (TextUtils.isEmpty(string) || string.equals("0")) {
                                        me.startActivity(new Intent(me, SelectiveSexActivity.class));
                                    } else if (string.equals("1")) {
                                        if (!TextUtils.isEmpty(data.get("invite_code"))) {
                                            AppManager.getInstance().killAllActivity();
                                            me.startActivity(new Intent(me, MainActivity.class));
                                            return;
                                        }
                                        me.startActivity(new Intent(me, WelcomeActivity.class));
                                    } else if (string.equals("2")) {
                                        if (!TextUtils.isEmpty(data.get("nickname"))) {
                                            AppManager.getInstance().killAllActivity();
                                            me.startActivity(new Intent(me, MainActivity.class));
                                            return;
                                        }
                                        EditorialMaterialsActivity.start(me, 1);
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {

                    }
                });


            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.d("zdl", "=========== db.getUserIcon()============" + throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {

            }
        });//授权回调监听，监听oncomplete，onerror，oncancel三种状态
        if (plat.isClientValid()) {
            //判断是否存在授权凭条的客户端，true是有客户端，false是无
        }
        if (plat.isAuthValid()) {
            //判断是否已经存在授权状态，可以根据自己的登录逻辑设置
            ToastUtil.show("已经授权过了");
            return;
        }
        ShareSDK.setActivity(me);
        //抖音登录适配安卓9.0
        plat.showUser(null);    //要数据不要功能，主要体现在不会重复出现授权界面
    }

    private void huanxin(Map<String, String> getData) {
        EMClient.getInstance().login(getData.get("id")+"m","123456",new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.d("huanxin", "登录聊天服务器成功！");
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.d("huanxin", "登录聊天服务器失败！");
            }
        });
    }
}
